<template>
  <div v-loading="isView" class="flow-containers" :class="{ 'view-mode': isView }">
    <el-container style="height: 100%">
      <el-header style="border-bottom: 1px solid rgb(218 218 218);height: auto;padding-left:0">
        <div class="bpmn-toolbar">
          <el-button-group>
            <el-tooltip effect="dark" content="打开文件" placement="bottom">
              <el-button size="mini" icon="el-icon-folder-opened" @click="openBpmn">
                <input type="file" ref="importRef" style="display: none" accept=".xml,.bpmn" @change="changeImportFile" />
              </el-button>
            </el-tooltip>
            <el-popover placement="bottom" trigger="hover">
              <template slot="reference">
                <el-button class="m-2" size="mini" icon="el-icon-view"></el-button>
              </template>
              <div style="display: grid;grid-template-columns: 1fr;grid-row-gap: 8px;padding: 8px 0;">
                <el-button size="mini" style="margin-left: 10px" @click="showXML">预览 XML</el-button>
                <el-button size="mini" @click="showJSON">预览 JSON</el-button>
              </div>
            </el-popover>
            <el-popover placement="bottom" trigger="hover">
              <template slot="reference">
                <el-button class="m-2" size="mini" icon="el-icon-download"></el-button>
              </template>
              <div style="display: grid;grid-template-columns: 1fr;grid-row-gap: 8px;padding: 8px 0;">
                <el-button size="mini" style="margin-left: 10px" @click="downloadProcessAsBpmn">导出为 Bpmn</el-button>
                <el-button size="mini" @click="downloadProcessAsXml">导出为 XML</el-button>
                <el-button size="mini" @click="downloadProcessAsSvg">导出为 SVG</el-button>
              </div>
            </el-popover>
          </el-button-group>

          <el-button-group>
            <el-tooltip effect="dark" content="自适应屏幕" placement="bottom">
              <el-button size="mini" icon="el-icon-rank" @click="fitViewport" />
            </el-tooltip>
            <el-tooltip effect="dark" content="放大" placement="bottom">
              <el-button size="mini" icon="el-icon-zoom-in" @click="zoomViewport(true)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="缩小" placement="bottom">
              <el-button size="mini" icon="el-icon-zoom-out" @click="zoomViewport(false)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="后退" placement="bottom">
              <el-button size="mini" icon="el-icon-back" @click="modeler.get('commandStack').undo()" />
            </el-tooltip>
            <el-tooltip effect="dark" content="前进" placement="bottom">
              <el-button size="mini" icon="el-icon-right" @click="modeler.get('commandStack').redo()" />
            </el-tooltip>
            <el-tooltip effect="dark" content="保存为草稿" placement="bottom">
              <el-button size="mini" icon="el-icon-document-add" @click="saveDraft" />
            </el-tooltip>
          </el-button-group>

          <el-button-group style="margin-left: auto;">
            <el-button size="mini" type="warning" @click="newDiagram">重新绘制</el-button>
            <el-button size="mini" type="primary" @click="save">保存模型</el-button>
            <el-popconfirm title="确定退出流程设计页面吗？" @confirm="goBack">
              <template #reference>
                <el-button size="mini" type="danger">关闭</el-button>
              </template>
            </el-popconfirm>
          </el-button-group>
        </div>
      </el-header>
      <!-- 流程设计页面 -->
      <el-container style="align-items: stretch">
        <el-main>
          <div ref="canvas" class="canvas layer-djs-grid" />
          <div class="button-group">
            <el-tooltip class="item" effect="dark" placement="left">
              <template slot="content">{{designer ? '收起' : '展开'}}</template>
              <el-button circle size="small" :icon="designer ? 'el-icon-d-arrow-right':'el-icon-d-arrow-left'" @click="togglePanel"/>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" placement="left">
              <template slot="content">{{ simulationStatus ? '退出模拟' : '开启模拟' }}</template>
              <el-button circle size="small" icon="el-icon-share" @click="processSimulation"/>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" placement="left">
              <template slot="content">{{ bpmnlintStatus ? '关闭检查' : '开启检查' }}</template>
              <el-button circle size="small" icon="el-icon-first-aid-kit" @click="handlerIntegrityCheck"/>
            </el-tooltip>
          </div>
        </el-main>

        <!--右侧属性栏-->
        <el-card shadow="never" :class="{'normalPanel':designer,'miniPanel':!designer}">
          <designer v-if="loadCanvas"></designer>
        </el-card>
      </el-container>
    </el-container>
  </div>
</template>

<script>
// 汉化
import customTranslate from './customPanel/customTranslate'
import Modeler from 'bpmn-js/lib/Modeler'
import Designer from './designer'
import getInitStr from './flowable/init'
import {StrUtil} from '@/utils/StrUtil'
// 引入flowable的节点文件
import FlowableModule from './flowable/flowable.json'
import customControlsModule from './customPanel'
import BpmnColorPickerModule from 'bpmn-js-color-picker';
import TokenSimulationModule from 'bpmn-js-token-simulation';
import GridModule from 'diagram-js-grid';
import { CreateAppendAnythingModule } from 'bpmn-js-create-append-anything';
import lintModule from 'bpmn-js-bpmnlint';
import bpmnLintConfig from './common/.bpmnlintrc';
import {addDraft, updateDraft} from "@/api/flowable/draft";
export default {
  name: "BpmnModel",
  components: {Designer},
  /** 组件传值  */
  props : {
    xml: {
      type: String,
      default: ""
    },
    isView: {
      type: Boolean,
      default: false
    },
    category: {
      type: [String , Number],
      default: null
    },
    draftId: {
      type: [String , Number],
      default: null
    },
  },
  data() {
    return {
      modeler: null,
      zoom: 1,
      loadCanvas: false,  // 当前组件渲染然后再加载canvas
      simulationStatus: false,
      bpmnlintStatus: false,
      simulation: true,
      designer: true,
    }
  },
  /** 传值监听 */
  watch: {
    xml: {
      handler(newVal) {
        this.toggleSideBar();
        if (StrUtil.isNotBlank(newVal)) {
          this.createNewDiagram(newVal)
        } else {
          this.newDiagram()
        }
      },
      immediate: true, // 立即生效
    },
  },
  computed: {
    additionalModules() {
      const Modules = [];
      Modules.push(customControlsModule);
      Modules.push(BpmnColorPickerModule);
      Modules.push(CreateAppendAnythingModule);
      Modules.push({ //汉化
        translate: ['value', customTranslate]
      });
      // 模拟流转模块
      if (this.simulation) {
        Modules.push(TokenSimulationModule);
      }
      // 流程校验
      Modules.push(lintModule);
      // 默认背景
      Modules.push(GridModule);
      return Modules;
    },
  },
  mounted() {
    /** 创建bpmn 实例 */
    const modeler = new Modeler({
      container: this.$refs.canvas,
      additionalModules: this.additionalModules,
      moddleExtensions: {
        flowable: FlowableModule
      },
      linting: {
        bpmnlint: bpmnLintConfig
      },
      keyboard: { bindTo: document },
    })
    this.modeler = modeler;
    // 注册 modeler 相关信息
    this.modelerStore.modeler = modeler;
    this.modelerStore.modeling = modeler.get("modeling");
    this.modelerStore.moddle = modeler.get("moddle");
    this.modelerStore.canvas = modeler.get("canvas");
    this.modelerStore.bpmnFactory = modeler.get("bpmnFactory");
    this.modelerStore.elRegistry = modeler.get("elementRegistry");
    // 存入当前流程分类
    if (this.category) {
      this.modelerStore.category = this.category;
    }
    // 直接点击新建按钮时,进行新增流程图
    if (StrUtil.isBlank(this.xml)) {
      this.newDiagram()
    } else {
      this.createNewDiagram(this.xml)
    }
    // 创建modeler事件
    this.$nextTick(() => {
      this.createModelerEvent(modeler)
    })
  },
  methods: {
    // 根据默认文件初始化流程图
    newDiagram() {
      this.createNewDiagram(getInitStr())
    },

    // 根据提供的xml创建流程图
    async createNewDiagram(data) {
      // 将字符串转换成图显示出来
      // data = data.replace(/<!\[CDATA\[(.+?)]]>/g, '&lt;![CDATA[$1]]&gt;')
      if (StrUtil.isNotBlank(this.modelerStore.modeler)) {
        data = data.replace(/<!\[CDATA\[(.+?)]]>/g, function (match, str) {
            return str.replace(/</g, '&lt;')
          }
        )
        try {
          await this.modelerStore.modeler.importXML(data)
          this.fitViewport()
        } catch (err) {
          console.error(err.message, err.warnings)
        }
      }
    },

    // 注册设计器点击事件
    createModelerEvent(modeler) {
      const that = this;
      // 流程校验
      modeler.on('linting.toggle', function (event) {
        that.bpmnlintStatus = event.active;
      });
    },

    // 让图能自适应屏幕
    fitViewport() {
      this.zoom = this.modelerStore.canvas.zoom('fit-viewport')
      const bbox = document.querySelector('.flow-containers .viewport').getBBox()
      const currentViewBox = this.modelerStore.canvas.viewbox()
      const elementMid = {
        x: bbox.x + bbox.width / 2 - 65,
        y: bbox.y + bbox.height / 2
      }
      this.modelerStore.canvas.viewbox({
        x: elementMid.x - currentViewBox.width / 2,
        y: elementMid.y - currentViewBox.height / 2,
        width: currentViewBox.width,
        height: currentViewBox.height
      })
      this.zoom = bbox.width / currentViewBox.width * 1.8
      this.loadCanvas = true;
    },

    // 放大缩小
    zoomViewport(zoomIn = true) {
      this.zoom = this.modelerStore.canvas.zoom()
      this.zoom += (zoomIn ? 0.1 : -0.1)
      this.modelerStore.canvas.zoom(this.zoom)
    },

    // 获取流程基础信息
    getProcess() {
      const element = this.getProcessElement()
      return {
        id: element.id,
        name: element.name,
        category: element.processCategory
      }
    },

    // 获取流程主面板节点
    getProcessElement() {
      const rootElements = this.modelerStore.modeler.getDefinitions().rootElements
      for (let i = 0; i < rootElements.length; i++) {
        if (rootElements[i].$type === 'bpmn:Process') return rootElements[i]
      }
    },

    // 保存xml
    async saveXML(download = false) {
      try {
        const {xml} = await this.modelerStore.modeler.saveXML({format: true})
        if (download) {
          this.downloadFile(`${this.getProcessElement().name}.bpmn20.xml`, xml, 'application/xml')
        }
        return xml
      } catch (err) {
        console.log(err)
      }
    },

    // 在线查看xml
    async showXML() {
      try {
        const xmlStr = await this.saveXML();
        this.$emit('showXML', xmlStr);
      } catch (err) {
        console.log(err)
      }
    },

    // 在线查看json
    async showJSON() {
      try {
        const xmlStr = await this.saveXML();
        const xml = await this.modelerStore.moddle.fromXML(xmlStr);
        const jsonStr = JSON.stringify(xml, null, 2);
        this.$emit('showJSON', jsonStr);
      } catch (err) {
        console.error(err);
      }
    },

    // 保存流程图为svg
    async saveImg(type = 'svg', download = false) {
      try {
        const {svg} = await this.modelerStore.modeler.saveSVG({format: true})
        if (download) {
          this.downloadFile(this.getProcessElement().name, svg, 'image/svg+xml')
        }
        return svg
      } catch (err) {
        console.log(err)
      }
    },

    // 保存流程图
    async save() {
      const process = this.getProcess()
      const xml = await this.saveXML()
      const svg = await this.saveImg()
      const result = {process, xml, svg}
      this.$emit('save', result)
      window.parent.postMessage(result, '*')
      // this.goBack();
    },

    // 打开流程文件
    openBpmn() {
      this.$refs.importRef && this.$refs.importRef.click();
    },
    changeImportFile() {
      const that = this;
      try {
        if (that.$refs.importRef && that.$refs.importRef.files) {
          const file = that.$refs.importRef.files[0];
          const reader = new FileReader();
          reader.readAsText(file);
          reader.onload = function () {
            const xmlStr = this.result;
            that.modelerStore.modeler.importXML(xmlStr);
          };
          that.$refs.importRef.value = null;
          that.$refs.importRef.files = null;
        }
      } catch (e) {
        console.error(e);
      }
    },

    async downloadProcess(type,) {
      const name = this.getProcessElement().name;
      try {
        const modeler = this.modelerStore.modeler;
        // 按需要类型创建文件并下载
        if (type === "xml" || type === "bpmn") {
          const {err, xml} = await modeler.saveXML();
          // 读取异常时抛出异常
          if (err) {
            console.error(`[Process Designer Warn ]: ${err.message || err}`);
          }
          const {href, filename} = this.setEncoded(type.toUpperCase(), name, xml);
          this.downloadFile(href, filename);
        } else {
          const {err, svg} = await modeler.saveSVG();
          // 读取异常时抛出异常
          if (err) {
            return console.error(err);
          }
          const {href, filename} = this.setEncoded("SVG", name, svg);
          this.downloadFile(href, filename);
        }
      } catch (e) {
        console.error(`[Process Designer Warn ]: ${e.message || e}`);
      }
    },
    downloadProcessAsBpmn() {
      this.downloadProcess("bpmn");
    },
    downloadProcessAsXml() {
      this.downloadProcess("xml");
    },
    downloadProcessAsSvg() {
      this.downloadProcess("svg");
    },

    // 根据所需类型进行转码并返回下载地址
    setEncoded(type, filename, data) {
      const encodedData = encodeURIComponent(data);
      return {
        filename: `${filename}.${type.toLowerCase()}`,
        href: `data:application/${type === "svg" ? "text/xml" : "bpmn20-xml"};charset=UTF-8,${encodedData}`,
        data: data
      };
    },

    // 文件下载方法
    downloadFile(href, filename) {
      if (href && filename) {
        const a = document.createElement("a");
        a.download = filename; //指定下载的文件名
        a.href = href; //  URL对象
        a.click(); // 模拟点击
        URL.revokeObjectURL(a.href); // 释放URL 对象
      }
    },

    /** 隐藏属性面板*/
    togglePanel() {
      this.designer = !this.designer;
    },

    /** 流程模拟器*/
    processSimulation() {
      this.simulationStatus = !this.simulationStatus;
      this.simulation && this.modeler.get("toggleMode").toggleMode();
    },

    /** 流程校验*/
    handlerIntegrityCheck() {
      const linting = this.modeler.get('linting')
      linting && linting.toggle();
    },

    // 保存草稿
    async saveDraft() {
      const process = this.getProcess();
      const xml = await this.saveXML();
      const params = {
        id: this.draftId,
        name: process.name,
        category: process.category,
        xml: xml,
        formId: this.modelerStore.formId,
      };
      try {
        const res = params.id != null ? await updateDraft(params) : await addDraft(params);
        if (res.code === 200) {
          this.$modal.msgSuccess("保存草稿成功");
          this.goBack();
        } else {
          this.$modal.msgError("保存草稿成功");
        }
      } catch (error) {
        this.$modal.msgError("保存草稿失败");
      }
    },

    /** 关闭当前标签页并返回上个页面 */
    goBack() {
      const obj = {path: "/flowable/definition", query: {t: Date.now()}};
      this.$tab.closeOpenPage(obj);
      this.toggleSideBar();
    },
    // 隐藏或显示侧边栏
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
  }
}


</script>

<style lang="scss">
/*左边工具栏以及编辑节点的样式*/
@import "~bpmn-js/dist/assets/bpmn-js.css";
@import "~bpmn-js/dist/assets/diagram-js.css";
@import "~bpmn-js/dist/assets/bpmn-font/css/bpmn.css";
@import "~bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css";
@import "~bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";
/*流程模拟器样式*/
@import "~bpmn-js-token-simulation/assets/css/bpmn-js-token-simulation.css";
/*流程校验样式*/
@import '~bpmn-js-bpmnlint/dist/assets/css/bpmn-js-bpmnlint.css';

.view-mode {
  .el-header, .el-aside, .djs-palette, .bjs-powered-by {
    display: none;
  }
  .el-loading-mask {
    background-color: initial;
  }
  .el-loading-spinner {
    display: none;
  }
}

.flow-containers {
  width: 100%;
  height: calc(100vh - 80px);
  .canvas {
    width: 100%;
    height: 100%;
    //background: url("")
  }
  .panel {
    position: absolute;
    right: 0;
    top: 50px;
    width: 300px;
  }
  .load {
    margin-right: 10px;
  }
  .normalPanel {
    width: 400px;
    height: 100%;
  }
  .miniPanel {
    width: 0;
    height: 0;
  }
  // 不显示自带流程模拟器开关
  .bts-toggle-mode {
    display: none;
  }

  .el-main {
    position: relative;
    padding: 0;
  }

  .el-main .button-group {
    display: flex;
    flex-direction: column;
    position: absolute;
    width: auto;
    height: auto;
    top: 10px;
    right: 10px;
  }

  .button-group .el-button {
    width: 100%;
    margin: 0 0 5px;
  }

  .bpmn-toolbar {
    width: 100%;
    height: min-content;
    box-sizing: border-box;
    padding: 8px 16px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    > div[class^='el-button-group'] + div[class^='el-button-group'] {
      margin-left: 16px;
    }

    .el-button__no-padding {
      padding: 0 15px;
      height: 32px;
    }
  }

  .el-card__body {
    padding: 10px;
  }
}
</style>
